package com.island.practice.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class DeletePersonServlet
 */
public class DeleteRoleServlet extends AbstractServlet {

	/**
	 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
	 * methods.
	 * 
	 * @param request
	 *            servlet request
	 * @param response
	 *            servlet response
	 */
	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String checkType = "false";
		String roleId = request.getParameter("roleId");

		Connection connection = null;
		PreparedStatement statement = null;

		try {
			connection = this.getConnection();
			connection.setAutoCommit(false);
			// check any person have no this role
			statement = connection.prepareStatement("SELECT *"
					+ "FROM PERSON_ROLE_RELATION " + "WHERE ROLE_ID = ? ");
			statement.setString(1, roleId);
			if (statement.executeQuery().next())
				checkType = "true";
			else {
				// delete role
				statement = connection.prepareStatement("DELETE "
						+ "FROM ROLE " + "WHERE ROLE_ID = ? ");
				statement.setString(1, roleId);
				statement.execute();
			}
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException("delete role failed", e);
		} finally {
			closeStatement(statement);
			closeConnection(connection);
		}
		
		request.setAttribute("checkType", checkType);
		// Forward to the jsp page for rendering
		request.getRequestDispatcher("/role/ListRole").forward(request,
				response);
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		this.processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		this.processRequest(request, response);
	}

}
